<template>
  <view class="coupon-page">
    <!-- 筛选区域 -->
    <view class="filter-section">
      <view class="filter-item">
        <picker @change="typeChange" :value="typeIndex" :range="typeOptions" range-key="label">
          <view class="picker-content">
            <text>优惠券类型：{{ typeOptions[typeIndex].label }}</text>
            <uni-icons type="bottom" size="12"></uni-icons>
          </view>
        </picker>
      </view>
    </view>

    <!-- 优惠券列表 -->
    <view class="coupon-list">
      <view class="coupon-item" v-for="(item, index) in couponList" :key="index">
        <view class="coupon-content">
          <view class="coupon-left">
            <view class="amount" :class="{'time-coupon': item.type === 'TIME'}">
              {{ formatValue(item) }}
            </view>
            <view class="condition">{{ formatCondition(item) }}</view>
          </view>
          <view class="coupon-right">
            <view class="title">{{ item.name }}</view>
            <view class="desc">{{ item.description || '暂无使用说明' }}</view>
            <view class="validity">{{ formatDate(item.validFrom) }} - {{ formatDate(item.validTo) }}</view>
            <view class="status-box">
              <text class="remain-count" v-if="item.totalQuantity - item.receivedQuantity > 0">
                剩余{{ item.totalQuantity - item.receivedQuantity }}张
              </text>
              <button 
                class="receive-btn" 
                :class="{'time-btn': item.type === 'TIME', 'disabled-btn': isExpired(item) || isNotStarted(item)}"
                @click="receiveCoupon(item)"
                :disabled="isExpired(item) || isNotStarted(item)"
              >
                {{ getBtnText(item) }}
              </button>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态显示 -->
      <view class="empty-state" v-if="couponList.length === 0">
        <image src="/static/images/empty.png" mode="aspectFit"></image>
        <text>暂无可用优惠券</text>
      </view>
    </view>
  </view>
</template>

<script>
import { getCouponList, receiveCoupon } from '@/api/coupon/coupon'

export default {
  data() {
    return {
      couponList: [],
      queryParams: {
        type: '',
      },
      typeIndex: 0,
      typeOptions: [
        { label: '全部类型', value: '' },
        { label: '满减券', value: 'AMOUNT' },
        { label: '折扣券', value: 'DISCOUNT' },
        { label: '全免券', value: 'FREE' },
        { label: '限时券', value: 'TIME' }
      ],
      currentDate: new Date().getTime()
    }
  },
  onLoad() {
    this.getList()
  },
  // 添加下拉刷新
  onPullDownRefresh() {
    this.getList().then(() => {
      uni.stopPullDownRefresh()
    })
  },
  methods: {
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    },
    
    // 类型选择改变
    typeChange(e) {
      this.typeIndex = e.detail.value
      this.queryParams.type = this.typeOptions[this.typeIndex].value
      this.handleSearch()
    },
    
    // 搜索处理
    handleSearch() {
      this.getList()
    },
    
    // 获取优惠券列表
    async getList() {
      try {
        uni.showLoading({
          title: '加载中'
        })
        const res = await getCouponList(this.queryParams)
        if (res.code === 200) {
          this.couponList = res.data
        } else {
          this.$modal.showToast(res.msg)
        }
      } catch (error) {
        this.$modal.showToast('获取优惠券列表失败')
        console.error('获取优惠券列表失败:', error)
      } finally {
        uni.hideLoading()
      }
    },

    // 领取优惠券
    async receiveCoupon(coupon) {
      if(this.isExpired(coupon)) {
        this.$modal.showToast('优惠券已过期')
        return
      }
      
      if(this.isNotStarted(coupon)) {
        this.$modal.showToast('优惠券活动未开始')
        return
      }

      if (coupon.receivedQuantity >= coupon.totalQuantity) {
        this.$modal.showToast('优惠券已领完')
        return
      }
      
      // 检查是否超过每人领取限制
      if (coupon.receivedQuantity >= coupon.perUserLimit) {
        this.$modal.showToast('已达到领取上限')
        return
      }

      try {
        const res = await receiveCoupon({ couponId: coupon.id })
        if (res.code === 200) {
          this.$modal.showToast('领取成功')
          this.getList() // 刷新列表
        } else {
          this.$modal.showToast(res.msg || '领取优惠券失败')
        }
      } catch (error) {
        this.$modal.showToast('领取优惠券失败')
        console.error('领取优惠券失败:', error)
      }
    },

    // 格式化优惠券面值显示
    formatValue(item) {
      switch(item.type) {
        case 'AMOUNT':
          return `¥${item.value}`
        case 'DISCOUNT':
          return `${item.value}折`
        case 'FREE':
          return '免费'
        case 'TIME':
          return `${item.value}小时`
        default:
          return item.value
      }
    },

    // 格式化使用条件显示
    formatCondition(item) {
      if (item.minAmount && item.minAmount > 0) {
        return `满${item.minAmount}可用`
      }
      switch(item.type) {
        case 'FREE':
          return '无门槛使用'
        case 'TIME':
          return '限时优惠'
        default:
          return ''
      }
    },

    // 判断优惠券是否过期
    isExpired(item) {
      const now = this.currentDate
      const validTo = new Date(item.validTo).getTime()
      return now > validTo
    },

    // 判断优惠券是否未开始
    isNotStarted(item) {
      const now = this.currentDate
      const validFrom = new Date(item.validFrom).getTime()
      return now < validFrom
    },

    // 获取按钮文本
    getBtnText(item) {
      if(this.isExpired(item)) {
        return '已过期'
      }
      if(this.isNotStarted(item)) {
        return '未开始'
      }
      if(item.receivedQuantity >= item.totalQuantity) {
        return '已领完'
      }
      if(item.receivedQuantity >= item.perUserLimit) {
        return '已达上限'
      }
      return '立即领取'
    }
  }
}
</script>

<style lang="scss" scoped>
.coupon-page {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.filter-section {
  background-color: #fff;
  padding: 20rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
  
  .filter-item {
    margin-right: 20rpx;
    flex: 1;
    
    .picker-content {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 10rpx 20rpx;
      background-color: #f8f8f8;
      border-radius: 8rpx;
    }
    
    .amount-input {
      padding: 10rpx 20rpx;
      background-color: #f8f8f8;
      border-radius: 8rpx;
    }
  }
}

.coupon-list {
  .coupon-item {
    background-color: #fff;
    border-radius: 12rpx;
    margin-bottom: 20rpx;
    
    .coupon-content {
      display: flex;
      padding: 20rpx;
    }

    .coupon-left {
      width: 200rpx;
      border-right: 1px dashed #ddd;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      .amount {
        color: #ff4444;
        font-size: 48rpx;
        font-weight: bold;
        &.time-coupon {
          color: #8a2be2;
        }
      }

      .condition {
        color: #666;
        font-size: 24rpx;
        margin-top: 10rpx;
      }
    }

    .coupon-right {
      flex: 1;
      padding-left: 20rpx;
      position: relative;

      .title {
        font-size: 32rpx;
        font-weight: bold;
        margin-bottom: 10rpx;
      }

      .desc {
        color: #666;
        font-size: 26rpx;
        margin-bottom: 10rpx;
      }

      .validity {
        color: #999;
        font-size: 24rpx;
      }

      .status-box {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        margin-top: 20rpx;

        .remain-count {
          color: #ff4444;
          font-size: 24rpx;
          margin-right: 20rpx;
        }

        .receive-btn {
          background-color: #ff4444;
          color: #fff;
          font-size: 26rpx;
          padding: 10rpx 30rpx;
          border-radius: 30rpx;
          border: none;

          &:disabled {
            background-color: #ccc;
          }

          &.time-btn {
            background-color: #8a2be2;
          }

          &.disabled-btn {
            background-color: #ccc !important;
            cursor: not-allowed;
          }
        }
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 0;
  
  image {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 20rpx;
  }
  
  text {
    color: #999;
    font-size: 28rpx;
  }
}
</style>
